import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { App } from 'antd';
import defaultSettings from '../config/defaultSettings';
import { AvatarDropdown } from './components';
import { queryCurrentUser } from './service/user';
const loginPath = '/login';

export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: object;
  loading?: boolean;
  fetchUserInfo?: () => Promise<object | undefined>;
}> {
  const fetchUserInfo = async () => {
    const user = await queryCurrentUser();

    if (!user) {
      history.push(loginPath);
      return null;
    }

    return user;
  };

  const { location } = history;
  if (location.pathname !== loginPath && location.pathname !== '/' ) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    avatarProps: {
      title: `${initialState?.currentUser?.username}-${initialState?.currentUser?.account}`,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <App>
          <div>{children}</div>
        </App>
      );
    },
    ...initialState?.settings,
  };
};
